var loginURL = "/template/system/login.html";
var validateActionAuthURL = "/system/validateActionAuth";

$(function() {
    // "".trim();
    String.prototype.trim = function() {
        return this.replace(/(^\s*)|(\s*$)/g, "");
    }
    String.prototype.text = function() {
        return this.replace(/\</g, "&lt;").replace(/\>/g, "&gt;");
    }
    String.prototype.isHtml = function() {
        return this.match(/<[^>]+>/g);
    }
    // new Date(r.createTime).pattern("yyyy-MM-dd HH:mm:ss")
    Date.prototype.pattern = function(fmt) {
        var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
            "H+": this.getHours(), //小时
            "m+": this.getMinutes(), //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds() //毫秒
        };
        var week = {
            "0": "天",
            "1": "一",
            "2": "二",
            "3": "三",
            "4": "四",
            "5": "五",
            "6": "六"
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        if (/(E+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "周") : "") + week[this.getDay() + ""]);
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    }
    // 轮换事件
    $.fn.toggle = function(fn, fn2) {
        var args = arguments,
            guid = fn.guid || $.guid++,
            i = 0,
            toggle = function(
                event) {
                var lastToggle = ($._data(this, "lastToggle" + fn.guid) || 0) % i;
                $._data(this, "lastToggle" + fn.guid, lastToggle + 1);
                event.preventDefault();
                return args[lastToggle].apply(this, arguments) || false;
            };
        toggle.guid = guid;
        while (i < args.length) {
            args[i++].guid = guid;
        }
        return this.click(toggle);
    };
    /**
     * 为容器里面加载数据 name = key
     * $('#addUpdateForm').loadData({nickName:"张三",age:14});
     */
    $.fn.loadData = function(jsons) {
        for (var name in jsons) {
            var dom = $(this).find("[name='" + name + "']");
            if (dom.length != 0) {
                var tagName = dom[0].tagName;
                if (tagName == "INPUT") {
                    dom.val(jsons[name]);
                } else if (tagName == "TEXTAREA") {
                    dom.text(jsons[name]);
                } else if (tagName == "SELECT") {
                    dom.val(jsons[name]);
                }
            }
        }
    };
    $.fn.clear = function() {
        var dom = $(this).find("[name]");
        for (var i = 0; i < dom.length; i++) {
            var tagName = dom[i].tagName;
            if (tagName == "INPUT") {
                dom.val("");
            } else if (tagName == "TEXTAREA") {
                dom.text("");
            } else if (tagName == "SELECT") {
                dom.val("");
            }
        }
    };
    /**
     * jquery.serializeJSON.js
     * 用法
     * $('#dict_dialog_form').formData(),
     * 如果remark为空字符串,则排除这个属性
     * $('#dict_dialog_form').formData(["remark"]),
     */
    $.fn.getData = function(option) {
        var json = $(this).serializeJSON();
        for (var i in json) {
            if (json[i] != "" || !(option && option instanceof Array)) {
                continue;
            }
            for (var j = 0; j < option.length; j++) {
                if (i == option[j]) {
                    delete json[i];
                }
            }
        }
        return json;
    };
    $.extend({
        /**
         * $.AJAX({});
         * 统一对error http状态码进行处理
         * 注意多加了个filter字段  属性中有filter字段且为true时 则拦截所有code!=200的结果只提示
         */
        "AJAX": function(options) {
            var successFc = options.success;
            var errorFc = options.error;
            options.success = function(result) {
                if ("filter" in options && options.filter && result.code != 200) {
                    layui.use('layer', function() {
                        var layer = layui.layer;
                        layer.msg(result.msg);
                    });
                    return;
                }
                if (successFc) {
                    (successFc)(result);
                }
            };
            options.error = function(XMLHttpRequest, textStatus, errorThrown) {
                if (XMLHttpRequest.status == 404) {
                    layui.use('layer', function() {
                        var layer = layui.layer;
                        layer.msg("请求链接不存在");
                    });
                    return;
                }
                if (XMLHttpRequest.status == 401) {
                    alert("您未登录或登录超时，请重新登录");
                    location.href = loginURL;
                    return;
                }
                if (XMLHttpRequest.status == 403) {
                    alert("您没有权限执行当前操作");
                    return;
                }
                if (XMLHttpRequest.status == 500) {
                    alert("系统还没准备好，请稍后重试");
                    return;
                }
                if (errorFc) {
                    (errorFc)(XMLHttpRequest, textStatus, errorThrown);
                }
            };
            $.ajax(options);
        },
        "auth": function() {
            var codes = [];
            $("[auth]").each(function() {
                codes[codes.length] = $(this).attr("auth");
            });
            if (codes.length > 0) {
                // 访问
                $.AJAX({
                    url: validateActionAuthURL,
                    data: {
                        codes: codes
                    },
                    type: "POST",
                    dataType: "json",
                    filter: true,
                    success: function(result) {
                        for (var code in result.data) {
                            if (result.data[code]) {
                                // 显示
                                $("[auth='" + code + "']").removeClass('hidden');
                            }
                        }
                    }
                });
            }
        },
        /**
         * 弹出询问框
         * $.confirm("OK?",function(){ alert(1);})
         */
        "confirm": function(msg, okFun) {
            layer.confirm(msg, {
                btn: ['确认', '取消']
            }, function(i) {
                if (okFun) {
                    (okFun)();
                }
                layer.close(i);
            }, function() {});
        },
        "alert": function(msg, okFun) {
            layer.open({
                content: msg,
                btn: ['确认'],
                yes: function(i) {
                    if (okFun) {
                        (okFun)();
                    }
                    layer.close(i);
                }
            });
        },
        /**
         * 获取表格选中的行 表格id 是否多选
         * 成功返回选中的行数据 失败则返回false
         * var rows = $.getCheckedRows(tableId,false);
         * if(!rows){
         *   return;
         * }
         */
        "getCheckedRows": function(tableId, multiple) {
            var table = layui.table;
            var rows = table.checkStatus(tableId).data;
            if (rows.length == 0) {
                layer.msg(multiple ? "请至少选中一行数据" : "请选中一行数据");
                return false;
            }
            if (!multiple && rows.length > 1) {
                layer.msg("只能选择一行数据");
                return false;
            }
            return rows;
        },
        /**
         * 根据id删除
         * tableId 表格id
         * multiple 是否可多选
         * url 删除请求的URL
         * filter 返回数据结果code != 200 的是否直接被拦截处理
         * success 返回数据结构后的执行的方法
         */
        "deleteByIds": function(tableId, multiple, url, filter, success) {
            var rows = $.getCheckedRows(tableId, multiple);
            if (!rows) {
                return;
            }
            $.confirm('您确定要删除选中的数据吗?', function() {
                var obj = {};
                if (multiple) {
                    var ids = [];
                    for (var i = 0; i < rows.length; i++) {
                        ids[i] = rows[i].id;
                    }
                    obj = {
                        "ids": ids
                    };
                } else {
                    obj = {
                        "id": rows[0].id
                    };
                }
                $.AJAX({
                    url: url,
                    type: "POST",
                    data: obj,
                    dataType: "json",
                    filter: filter,
                    success: function(result) {
                        if (result.code == 200) {
                            layer.msg("删除成功");
                        }
                        if (success) {
                            (success)(result);
                        }
                    }
                });
            });
        }
    });
    $.auth();
});

/**
 * id		table标识
 * ele		dom节点
 * fliter	dom节点上的filter
 * cols 		二维数组
 * whereObj	查询条件
 */
function initTab(tableId, ele, fliter, url, cols, whereObj, istotal,res) {
    layui.use('table', function() {
        var table = layui.table;
        table.render({
            method:'POST',
            id: tableId,
            autoSort: false,
            elem: ele,
            height: 480,
            url: url,
            even: true,
            where: whereObj,
            totalRow: istotal, //开启合计行
            page: true,
            cols: cols,
            response: {
                errorcode: 0 //重新规定成功的状态码为 200，table 组件默认为 0
              },
            parseData: function(res) {
                console.log(res);
                // res.binderList=[]
                if(res.errorcode!=0){
                    res.binderList=[]
                }
                if(res.userList){
                    return {
                        "code": res.errorcode,
                        "msg": res.resultmsg, //解析提示文本
                        "total": res.userList.length+1,
                        "data": res.userList
                    };
                }
                if(res.deviceList){
                    return {
                        "code": res.errorcode,
                        "msg": res.resultmsg, //解析提示文本
                        "total": res.deviceList.length+1,
                        "data": res.deviceList
                    };
                }
                if(res.binderList){
                    return {
                        "code": res.errorcode,
                        "msg": res.resultmsg, //解析提示文本
                        "total": res.binderList.length+1,
                        "data": res.binderList
                    };
                }
				if(res.paraList){
                    return {
                        "code": res.errorcode,
                        "msg": res.resultmsg, //解析提示文本
                        "total": res.paraList.length+1,
                        "data": res.paraList
                    };
                }
              
            }
        });
    });
}



/**
 * 获取url参数
 * @param name
 * @returns {*}
 */
function getUrlPart(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}


function isEmptyObject(obj) {
    for (var key in obj) {
        return false; //返回false，不为空对象
    }
    return true; //返回true，为空对象
}

function visitImg(imgUrl) {
    layer.photos({
        photos: {
            "title": "", // 相册标题
            "id": 123, // 相册id
            "start": 0, // 初始显示的图片序号，默认0
            "data": [ // 相册包含的图片，数组格式
                {
                    "alt": "图片名",
                    "pid": 666, // 图片id
                    "src": imgUrl, // 原图地址
                    "thumb": "" // 缩略图地址
                }
            ]
        }
    });
}

function saveStorage(key, value) {
    var va = value;
    if (window.localStorage[key] == "undefined" || window.localStorage[key] == undefined || window.localStorage[key] != value) {
        window.localStorage[key] = value;
    } else {
        va = window.localStorage[key];
    }
    return va;
}


function timestampToTime(timestamp) {
    var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() + ' ';
    return Y + M + D;
}

// function getExpress(no){
//     var url ="https://biz.trace.ickd.cn/auto/800932074?mailNo="+no
//     var result ='';
//     $.ajaxSettings.async = false;
//     $.get(url, null, function(data, textStatus, req) {
//         result=data;
//     });
//     return result;
// }